﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace MadiFracas
{
	public class CountryManager
	{
		const int MIN_VALUE = 10;
		const int MAX_VALUE = 100;
		const int AVG_COUNTRY_SIZE = 2;

		Random random = new Random(DateTime.Now.Millisecond);

		public Point Size { get; private set; }
		public int[,] Matriz { get; private set; }
		public List<int> Countries { get; private set; }

		public CountryManager(int width, int height)
		{
			Size = new Point(width, height);
			Matriz = new int[width, height];
			Countries = new List<int>();

			inicializar();

			for (int i = 0; i < 4; i++)
			{
				crearMesetas();
			}
		}

		private void inicializar()
		{
			// Generar matriz de numeros aleatorios
			for (int i = 0; i < Size.X; i++)
			{
				for (int j = 0; j < Size.Y; j++)
				{
					Matriz[i, j] = random.Next(MIN_VALUE, MAX_VALUE);
				}
			}
		}

		private void crearMesetas()
		{
			// Encuentra un punto aleatorio del mapa
			int i, j;

			int x = random.Next(0, Size.X);
			int y = random.Next(0, Size.Y);
			int countryNumber = Matriz[x, y];
			
			if (!Countries.Contains(countryNumber))
			{
				int countrySize = random.Next(0, 2) + AVG_COUNTRY_SIZE;

				for (i = Util.max(x - countrySize, 0); i < Util.min(x + countrySize, Size.X); i++)
				{
					for (j = Util.max(y - countrySize, 0); j < Util.min(y + countrySize, Size.Y); j++)
					{
						Matriz[i, j] = countryNumber;
					}
				}

				Countries.Add(countryNumber);
			}
		}

		public override string ToString()
		{
			string str = "";

			for (int i = 0; i < Size.X; i++)
			{
				for (int j = 0; j < Size.Y; j++)
				{
					str += Matriz[i, j].ToString() + " ";
				}
				str += "\n";
			}

			return str;
		}
	}
}
